// pages/index/wineShop/wineShop.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index:0,
    active:false,
    currentIndex:0,
    id:-1,
    goods:[],
    cover2:false,
    goods2:false,
    allCount:0,
    allPrice:0,
    house_num:0,
    activeS:false,
    all:true,
    simple:false,
    wineOrder:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log('options',options)
  //  if(options.wineOrder==1){
  //     this.setData({
  //       goods: []
  //     })
  //  }
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    wx.getSystemInfo({
      success(res) {
        // console.log(res)
        _this.setData({
          screenHeight: res.screenHeight
        })
      }
    })
  
    wx.request({
      url: app.globalData.baseUrl + '/api/house/house_num',
      data: {
        session_key: app.gs()
      },
      success(res) {
        let houses = res.data.data.house;
        let num = res.data.data.num;
        let hous = [];
        let houNum;
        for (let i = 0; i < houses.length; i++) {
          hous[i] = houses[i].name
        }
        hous.unshift('选择房号');
        if (res.data.data.num.is_scan == 1) {
          if (res.data.data.num.house == '选择房号') {
            houNum = hous[0]
          } else {
            houNum = res.data.data.num.house
          }

        } else {
          houNum = hous[0]
        }
        _this.setData({
          hous: hous,
          num: num,
          houses: houses,
          houseIndex: res.data.data.num.house,
          houNum: houNum,
         
        })
      }
    })
    let drinksShop = wx.getStorageSync('drinksShop');
    let allPrice = wx.getStorageSync('allPrice');
    let allCount = wx.getStorageSync('allCount');
    let goods = wx.getStorageSync('goods');
    console.log('drinksShop.length', drinksShop.length)
    if (drinksShop.length) {
      _this.setData({
        drinksShop: drinksShop,
        goods:goods,
        allPrice:allPrice,
        allCount:allCount
      })
      // return
    }else {
      wx.request({
        url: app.globalData.baseUrl + '/api/drinks/index',
        data: {
          session_key: app.gs()
        },
        success: function (res) {
          console.log(res)
          var drinksShop = res.data.data;
          _this.setData({
            drinksShop: drinksShop,
            goods: [],
            allPrice: 0,
            allCount: 0
          })
        }
      })
    }
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  bindPickerChange: function (e) {
    let _this = this;
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    let index = e.detail.value;
    // console.log(index)
    let ind = parseInt(index) - 1;
    // console.log(ind)
    let houseId, house_num;
    let houseIndex = _this.data.houseIndex;
    let num = _this.data.num;
    if (ind == -1) {
      houseId = -1,
      house_num = _this.data.hous[0]
      houseIndex = _this.data.hous[0]
    } else {
      houseId = _this.data.houses[ind].id;
      house_num = _this.data.houses[ind].name;
      houseIndex = _this.data.houses[ind].name
    }
    num.house = house_num
    _this.setData({
      index: index,
      houseId: houseId,
      house_num: house_num,
      houseIndex: houseIndex,
      houNum: house_num,
      num:num
    })
  },
  currentKind(e){
    // console.log(e)
    var that = this;
    var index = e.currentTarget.dataset.index;
    var drinksShop = that.data.drinksShop;
    
    // for (var i=0; i <  conLs.length;i++){
    //   conLs[i].active =''
    // }
    // 遍历数组for...of
    var con;
    for (con of drinksShop){
      con.active = ''
    }
    // console.log(conLs)
    drinksShop[index].active = 'active'
    that.setData({
      drinksShop: drinksShop,
      id:index,
      all:false,
      simple:true
    })
  },
  // ================不点击左侧时的增加减少商品=================
  addNum1(e){
    var that = this;
    var goods = [];
    var drinksShop = this.data.drinksShop;
    // console.log(e)
    // console.log(drinksShop)
    // console.log(e.currentTarget.dataset.findex)
    var vase = drinksShop[e.currentTarget.dataset.findex].drinks[e.currentTarget.dataset.sindex].vase;
    if(e.currentTarget.id == 'two'){
      if (parseInt(vase) > 0){
        vase = parseInt(vase) - 1
      }else {
        vase = vase
      }
      // console.log(vase)
    }else {
      vase = parseInt(vase) +1
      // console.log(vase)
    }
    drinksShop[e.currentTarget.dataset.findex].drinks[e.currentTarget.dataset.sindex].vase = vase
    // goods.push(drinksShop[e.currentTarget.dataset.findex].drinks[e.currentTarget.dataset.sindex])
    var allPrice = 0;
    var allCount = 0;
    for(let i = 0;i< drinksShop.length;i++){
      let drinks = drinksShop[i].drinks;
      if (drinks) {
        for (let j = 0; j < drinks.length; j++) {
          if (drinks[j].vase > 0) {
            goods.push(drinks[j]);
            allPrice = allPrice + Math.floor(drinks[j].price * 100) / 100 * parseInt(drinks[j].vase);
            allCount = allCount + parseInt(drinks[j].vase)
          }
        }
      }
    
    }
    // console.log(goods)
    wx.setStorageSync('goods', goods);
    wx.setStorageSync('allPrice', allPrice);
    wx.setStorageSync('allCount', allCount);
    wx.setStorageSync('drinksShop', drinksShop);
    allPrice = Math.floor(allPrice * 100) / 100;
    that.setData({
      drinksShop: drinksShop,
      goods:goods,
      allPrice:allPrice,
      allCount: allCount
    })
  },
  // =====================点击左侧列表后左侧增加减少购物车里面的商品======================
  addNum2(e) {
    let that = this;
    // 购物车商品
    let goods = that.data.goods;
    // 子选择序号
    let index = e.currentTarget.dataset.sindex;
    // 所有商品
    let drinksShop = that.data.drinksShop;
    // 母选择序号
    let id = that.data.id;
    // console.log('addNum2',drinksShop[id])
    let findex = e.currentTarget.dataset.findex;
    // 选择的数量
    let vase = drinksShop[id].drinks[index].vase;
    // 获取购物车商品数量和总价
    let allCount = that.data.allCount;
    let allPrice = that.data.allPrice;
    let flag = false;

    // 没有数据

    if(!goods.length){
      drinksShop[id].drinks[index].vase = 1;
      // console.log(drinksShop[id].drinks[index].vase)
      allCount = drinksShop[id].drinks[index].vase;
      // console.log(allCount)

      allPrice = drinksShop[id].drinks[index].price;
      // console.log(allPrice)
      goods.push(drinksShop[id].drinks[index])
      // console.log('goodsgoods',goods)
      
    // 有数据
    }else{
        // 遍历购物车
      for (let i = 0; i < goods.length; i++) {
        // 判断是否存在  id  相等的商品
        if (goods[i].id == findex) {
          // 判断是否是减少
          flag = true;
          if (e.currentTarget.id == 'two') {
            if (goods[i].vase >=1){
              goods[i].vase = vase - 1;
              drinksShop[id].drinks[index].vase = vase -1;
            }else {
              goods[i].vase = 0;
              drinksShop[id].drinks[index].vase = 0;
            }
              
          } else if (e.currentTarget.id == 'three') {
            // 判断是否是增加
            goods[i].vase += 1;
            drinksShop[id].drinks[index].vase += 1;
          }
        }
        
      }
      if(!flag){
        
        if (e.currentTarget.id == 'two') {
           // 判断是否是减少
          return
        } else if (e.currentTarget.id == 'three') {
          // 判断是否是增加
          goods.push(drinksShop[id].drinks[index])
         
          goods[goods.length-1].vase = 1;
          drinksShop[id].drinks[index].vase = 1;
          // console.log('goods', drinksShop[id].drinks[index])
          // console.log('goods', goods)
        }
      }
    }
    allCount = 0;
    allPrice = 0;
    for (let i = 0; i < goods.length; i++) {
      allCount += parseInt(goods[i].vase);
      allPrice += parseInt(goods[i].vase) * Math.floor(goods[i].price * 100) / 100
    }
    allPrice = Math.floor(allPrice * 100) / 100;
    wx.setStorageSync('goods', goods);
    wx.setStorageSync('allPrice', allPrice);
    wx.setStorageSync('allCount', allCount);
    wx.setStorageSync('drinksShop', drinksShop);
    that.setData({
      goods: goods,
      allPrice: allPrice,
      allCount: allCount,
      drinksShop: drinksShop
    })
  },
//  ============点击购物车图标后的增加减少商品==================
  addNum3(e) {
    console.log(e)
    let that = this;
    let goods = that.data.goods;
    let index = e.currentTarget.dataset.sindex;
    let drinksShop = that.data.drinksShop;
    let allCount = 0;
    let allPrice = 0;


   for(let i = 0;i <drinksShop.length;i++){
    //  外层循环
     for (let j = 0; j < drinksShop[i].drinks.length;j++){
      //  内层循环
       if (goods[index].id == drinksShop[i].drinks[j].id){
        //  判定是否id相等
         if(e.currentTarget.id=='two'){
          //  判定是否是减少
            if(goods[index].vase>=1){
              goods[index].vase -= 1
            }else {
              goods[index].vase = 0
            }
            
         }else if(e.currentTarget.id == 'three'){
          //  判定是否是增加
            goods[index].vase += 1
         }
         that.setData({
           i:i,
           j:j
         })


        //  return

        //  console.log('i', i, 'j', j)
         drinksShop[i].drinks[j].vase = goods[index].vase
         for (let k = 0; k < goods.length; k++) {
           allCount += parseInt(goods[k].vase);
           allPrice += parseInt(goods[k].vase) * Math.floor(goods[k].price*100)/100
         }
        //  console.log(allPrice)
         wx.setStorageSync('goods', goods);
         wx.setStorageSync('allPrice', allPrice);
         wx.setStorageSync('allCount', allCount);
         wx.setStorageSync('drinksShop', drinksShop);
         that.setData({
           goods: goods,
           allCount: allCount,
           allPrice: allPrice,
           drinksShop: drinksShop
         })
       }

     }
   }


 
  },
  // ===========================================
  closeaddNum(e){
    this.setData({
      active:false
    })
  },
  hideBottom(){
    this.setData({
      cover2: false,
      goods2: false
    })
  },
  goodsShow(e){
    var that = this;
    var cover2 = that.data.cover2;
    var goods2 = that.data.goods2;
    if(cover2 == true){
      that.setData({
        cover2: false,
        goods2: false
      })
    }else {
      that.setData({
        cover2: true,
        goods2: true
      })
    }
  },
  // showToastOrder(e){
  //   this.setData({
  //     activeS:true
  //   })
  // },
  orderPay(e){
    let that = this;
    var goodDrink = [];
    let goods = that.data.goods;
    let house_num = that.data.houNum;
    console.log()
    let drinksShop = that.data.drinksShop
   if (that.data.num.is_scan==0){
      if (house_num == 0) {
        wx.showToast({
          title: '请输入房号',
        })
        return
      }
    }
    else if (that.data.num.is_scan == 1){
      if (that.data.num.house!='选择房号'){
        house_num = that.data.num.house
      } else if (that.data.num.house == '选择房号') {
        // console.log('11111111111')
        wx.showToast({
          title: '选择房号',
        })
          return
      } else if (that.data.num.house == 'undefined'){
        wx.showToast({
          title: '选择房号',
        })
        return
      }
    }
  
    if(!goods.length) {
      wx.showToast({
        title: '请选择酒水',
      })
      return 
    }
    for (var i = 0; i < goods.length;i++){
      // console.log(goods[i].id)
      // console.log(goods)
      var con = {}
      con.goods_id = goods[i].id;
      con.buyNum = goods[i].vase;
      // console.log(con)
      goodDrink[i] = con;
     
    }
    // console.log('goodDrink',goodDrink)
    // JSON字符串转化方法
    let drinks = JSON.stringify(goodDrink);
    // console.log('arr',JSON.stringify(this.data.goods))
    // console.log('drinks',drinks)
    app.wxrequest({
      url: app.globalData.baseUrl +'/api/drinks/drinks_buy',
      data: {
        session_key: app.gs(),
        drinks:drinks,
        house_num: house_num,
        order_price:that.data.allPrice
      },
      success:function(res){
        // console.log(res)
        wx.hideLoading();
        wx.setStorageSync('drinksShop', drinksShop);
        wx.navigateTo({
          url: 'orderPay/orderPay?id=' + res.data.data.id + '&drinks=' + drinks + '&house_num=' + that.data.houNum+'&order_price='+that.data.allPrice+'&order_id='+res.data.data.id+'&coupon=0'+"&wineOrder=0",
        })
      }
    })
   
   
  },
  inputValue(e){
    // console.log(e)
    this.setData({
      house_num:e.detail.value
    })
  },
  close(e){
    this.setData({
      activeS:false
    })
  },
  // scanCode(e){
  //   wx.scanCode({
  //     success(res){
  //       console.log(res)
  //     }
  //   })
  // },
  saoma(e) {
    var _this = this;
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        let scan = res.path;
        let path = scan.split('?')[0];
        //      分配房号-index
        if (path == 'pages/index/index') {
          let house_num = scan.match(/scene=(\S*)/)[1];

          wx.request({
            url: app.globalData.baseUrl + '/api/house/band',

            data: {
              session_key: app.gs(),
              house_num: house_num
            },
            success(res) {
              // console.log('success', res)


              if (res.data.message == 200) {
                wx.showToast({
                  title: '确认完成'
                })
                // setTimeout(function () {
                //   wx.switchTab({
                //     url: '../../index/index'
                //   })
                // }, 2000)

             
                wx.request({
                  url: app.globalData.baseUrl + '/api/house/house_num',
                  data: {
                    session_key: app.gs()
                  },
                  success(res) {
                    // console.log('house-res', res)
                    let houses = res.data.data.house;
                    let num = res.data.data.num;
                    let hous = [];
                    let houNum;
                    for (let i = 0; i < houses.length; i++) {
                      hous[i] = houses[i].name
                    }
                    hous.unshift('选择房号');
                    // console.log('res.data.data.num', res.data.data.num)
                    if (res.data.data.num.is_scan == 1) {
                      if (res.data.data.num.house == '选择房号') {
                        houNum = hous[0]
                      } else {
                        houNum = res.data.data.num.house
                      }

                    } else {
                      houNum = hous[0]
                    }
                    _this.setData({
                      hous: hous,
                      num: num,
                      houses: houses,
                      houseIndex: res.data.data.num.house,
                      houNum: houNum
                    })
                  }
                })
              }
            }
          })
        }
      }
    })
  }
})